// This File is part of the "nyaqt" Project
// 
// Copyright  2009 sometmes@gmail.com
// All rights reserved
// 
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.



using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using nyaqt.Plugins;
using System.Configuration;

namespace nyaqt
{
    static class Program
    {
        static TestCommand _testCommand = null;
        static AppDomain _testCommandAppDomain = null;

        public static TestCommand TestCommand
        {
            get { return Program._testCommand; }
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //System.Data.DataSet ds = new System.Data.DataSet();
            //System.Data.DataTable t = ds.Tables.Add();
            //t.Columns.Add("uno",typeof(int));
            //t.Columns.Add("dos");
            //ds.Tables[0].Rows.Add(1, "a");
            //ds.Tables[0].Rows.Add(2, "b");
            //ds.Tables[0].Rows.Add(3, "c");

            //ds.Tables[0].Rows[0].BeginEdit();
            //ds.Tables[0].Rows[0].
            //ds.Tables[0].Rows[0][0] = "uno";
            //ds.Tables[0].Rows[0].BeginEdit();


            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                string cmd = GetCommandLineValue("TestCommand");
                if (cmd != null)
                {
                    string[] parts = cmd.Split(',');
                    string assemblyFileName = parts[1];
                    string config = assemblyFileName + ".dll.config";
                    AppDomainSetup setup = new AppDomainSetup();
                    if (File.Exists(Path.Combine(Application.StartupPath, @"DropReferences\" + config)))
                        setup.ConfigurationFile = config;
                    else
                    {
                        config = assemblyFileName + ".exe.config";
                        if (File.Exists(Path.Combine(Application.StartupPath, @"DropReferences\" + config)))
                            setup.ConfigurationFile = config;
                    }
                    if (setup.ConfigurationFile != null)
                    {
                        AppDomain d = AppDomain.CreateDomain(Path.GetFileName(Application.ExecutablePath), null, setup);
                        d.ExecuteAssembly(Application.ExecutablePath);
                        return;
                    }
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            LoadHardCodedSettings();
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            ProcessCommandLineArgs();
            Application.Run(new QueryWindowForm());
        }

        static string GetCommandLineValue(string param)
        {
            string[] args = Environment.GetCommandLineArgs();
            string cmd = "/" + param + ":";
            foreach (string arg in args)
            {
                if (arg.StartsWith(cmd, StringComparison.CurrentCultureIgnoreCase))
                {
                    string val = arg.Substring(cmd.Length);
                    return val;
                }
            }
            return null;
        }

        private static void ProcessCommandLineArgs()
        {
            string[] args = Environment.GetCommandLineArgs();
            foreach (string arg in args)
            {
                if (arg.StartsWith("/TestCommand:", StringComparison.CurrentCultureIgnoreCase))
                {
                    string testCommandTypeQualified = arg.Substring("/TestCommand:".Length);
                    LoadTestCommand(testCommandTypeQualified);
                }
            }
        }

        private static void LoadTestCommand(string testCommandTypeQualified)
        {
            //Loading in nyaqt appdomain
            Type t = Type.GetType(testCommandTypeQualified);
            if (!(typeof(TestCommand).IsAssignableFrom(t)))
                throw new ArgumentException("Test command should implement interface \"nyaqt.Plugins.ITestCommand\"");

            _testCommand = Activator.CreateInstance(t) as TestCommand;
            _testCommand.BuildCommand();

            ////Loading in a brand new domain with his own config
            //AppDomainSetup setup = new AppDomainSetup();
            //setup.ApplicationBase = Path.Combine(Application.StartupPath, "DropReferences");
            //string[] parts = testCommandTypeQualified.Split(',');
            //string typeName = parts[0];
            //string assemblyFileName = parts[1];
            //string config = assemblyFileName + ".dll.config";
            //parts = testCommandTypeQualified.Split(new char[] { ',' }, 2);
            //string assemblyFullName = parts[1];
            //if (File.Exists(Path.Combine(setup.ApplicationBase, config)))
            //    setup.ConfigurationFile = config;
            //else
            //{
            //    config = assemblyFileName + ".exe.config";
            //    if (File.Exists(Path.Combine(setup.ApplicationBase, config)))
            //        setup.ConfigurationFile = config;
            //}
            //_testCommandAppDomain = AppDomain.CreateDomain("TestCommandDomain", null, setup);
            //object o = _testCommandAppDomain.CreateInstanceAndUnwrap(assemblyFullName, typeName);
            //_testCommand = o as TestCommand;
            //_testCommand.BuildCommand();
        }

        static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string[] parts = args.Name.Split(',');
            string dynpath = Path.Combine(Application.StartupPath, "DropReferences\\" + parts[0] + ".dll");
            Assembly a = null;
            if (File.Exists(dynpath))
                a = Assembly.LoadFile(dynpath);
            return a;
        }

        static void Application_ApplicationExit(object sender, EventArgs e)
        {
            My.Settings.Save();
        }
        
        private static void LoadHardCodedSettings()
        {
            //SimpleConnectionEditorPlugin.RegisterPlugin("System.Data.SqlClient", "nyaqt.MsSqlPlugIn.SimpleConnectionEditor");
            //SimpleConnectionEditorPlugin.RegisterPlugin("Mono.Data.SybaseClient", "nyaqt.MonoSybasePlugin.SimpleConnectionEditor, nyaqt.MonoSybasePlugin");
            //SimpleConnectionEditorPlugin.RegisterPlugin("Mono.Data.SybaseClient", "nyaqt.SimpleConnectionEditorType1, nyaqt");
            //SimpleConnectionEditorPlugin.RegisterPlugin("Sybase.Data.AseClient", "nyaqt.SimpleConnectionEditorType1, nyaqt");

            SimpleConnectionEditorPlugin.RegisterPlugin("Mono.Data.SybaseClient", "nyaqt.MonoSybasePlugin.SybaseSimpleConnectionEditor2, nyaqt.MonoSybasePlugin");
            ConnectionPropertiesPlugin.RegisterPlugin("Mono.Data.SybaseClient", "nyaqt.MonoSybasePlugin.ConnectionProperties, nyaqt.MonoSybasePlugin", 2);


            SimpleConnectionEditorPlugin.RegisterPlugin("Sybase.Data.AseClient", "nyaqt.MonoSybasePlugin.SybaseSimpleConnectionEditor2, nyaqt.SybaseAsePlugin");
            ConnectionPropertiesPlugin.RegisterPlugin("Sybase.Data.AseClient", "nyaqt.SybaseAsePlugin.ConnectionProperties,nyaqt.SybaseAsePlugin", 1);

            SimpleConnectionEditorPlugin.RegisterPlugin("System.Data.SqlClient", "nyaqt.MsSqlClientPlugin.MsSqlClientSimpleConnectionEditor2, nyaqt.MsSqlClientPlugin");
            ConnectionPropertiesPlugin.RegisterPlugin("System.Data.SqlClient", "nyaqt.MsSqlClientPlugin.ConnectionProperties, nyaqt.MsSqlClientPlugin", 2);
        

            //My.Settings.RecentConnections.Clear();
            //My.Settings.RecentConnections.Add(new ConnectionInfoList("uno"));
            //My.Settings.RecentConnections[0].Connections.Add(new ConnectionInfo());
            //My.Settings.RecentConnections[0].Connections[0].ConnectionString = "AAAAAAAAAAAAAAAAAAAAA";
            //My.Settings.RecentConnections[0].Connections.Add(new ConnectionInfo());
            //My.Settings.RecentConnections[0].Connections[1].ConnectionString = "BBBBBBBBBBBBBBBBBBBBB";
            //My.Settings.RecentConnections[0].Connections.Add(new ConnectionInfo());
            //My.Settings.RecentConnections[0].Connections[2].ConnectionString = "CCCCCCCCCCCCCCCCCCCCC";
            //My.Settings.RecentConnections.Add(new ConnectionInfoList("dos"));
            //My.Settings.RecentConnections[1].Connections.Add(new ConnectionInfo());
            //My.Settings.RecentConnections[1].Connections[0].ConnectionString = "2222222222222222222222";
            //My.Settings.RecentConnections.Add(new ConnectionInfoList("tres"));
            //My.Settings.RecentConnections[2].Connections.Add(new ConnectionInfo());
            //My.Settings.RecentConnections[2].Connections[0].ConnectionString = "3333333333333333333333";

            //My.Settings.Save();
        }

        static void LoadUserPreferences()
        {
            //string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            //path = Path.Combine(path, "nyaqt\\Preferences.xml");
            ////if (File.Exists(path))
            //object ol = My.Settings.RecentConnections;
            ////RecentConnectionList l = new RecentConnectionList();
            //ConnectionInfo r = new ConnectionInfo();
            ////l.Add(r);
            //r.ConnectionString = "1";
            //r.Password = "2";
            //r.Created = DateTime.Now;
            //My.Settings.RecentConnections.Add(r);
            //My.Settings.Save();
        }
    }
}
































